﻿using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Data.Objects;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace System.Linq
{
    public static class LinqExtensions
    {
        public static IndexView ToIndexView<T>(this ObjectSet<T> me, string where = null, string order = null, bool desc = false, int index = 0, int size = 20, string query = null, params string[] include_tables) where T : class
        {
            var oq = string.IsNullOrEmpty(where) ?
                me.OrderBy("it." + order + (desc ? " desc" : "")) :
                me.Where(where).OrderBy("it." + order + (desc ? " desc" : ""));

            foreach (string include in include_tables)
            {
                oq = oq.Include(include);
            }

            var q = oq.AsQueryable<T>();
            int count = q.Count();

            q = q.Skip(index * size).Take(size);

            return new IndexView(q, index, size, count, order, desc, query);
        }

        public static string NoInjection(this string query)
        {
            if (string.IsNullOrEmpty(query))
                return null;
            return query.Trim().Replace("'", "''");
        }

        public static IEnumerable<SelectListItem> GetItemList<T>(this ObjectSet<T> me, string defaultvalue = null, string textfield = "display", string valuefield = null, string where = null, string order = null) where T : class
        {
            if (string.IsNullOrEmpty(valuefield))
            {
                valuefield = textfield;
            }
            if (string.IsNullOrEmpty(order))
                order = valuefield;
            return new SelectList(me.Where(where).OrderBy(order), valuefield, textfield, defaultvalue);
        }

        public static IEnumerable<SelectListItem> GetItemListByTypeCode<T>(this ObjectSet<T> me, string typecode, string defaultvalue = null, string textfield = "display", string valuefield = null, string typefield = "typecode", string order = null) where T : class
        {
            if (string.IsNullOrEmpty(valuefield))
            {
                valuefield = textfield;
            }
            if (string.IsNullOrEmpty(order))
                order = "it." + valuefield;
            SelectList list = new SelectList(me.Where("it." + typefield + "='" + typecode + "'").OrderBy(order), valuefield, textfield, defaultvalue);

            return list;
        }
    }
}